package com.qf.service;

import com.qf.constant.CacheConstants;
import com.qf.model.StandardSubmit;
import com.qf.service.api.CacheService;
import com.qf.util.PushMsgUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * 策略执行器
 * @author 何星宇
 * @version V1.0
 * @Date 2021/11/23 19:23
 */

@Component
@Slf4j
public class StrategyExecutor {

    //循环依赖--三级缓存--SingletonObjects(Map,所有由Spring构建的单例对象，都存放到了这个Map集合中)
    //1.获取全部可以执行的全部Strategy对象
    @Autowired
    private Map<String,Strategy> strategyObjects;
    @Autowired
    private CacheService cacheService;
    @Autowired
    private PushMsgUtil pushMsgUtil;

    public void execute(StandardSubmit standardSubmit) throws IOException {

        System.out.println(strategyObjects);

        //2.查询缓存中提供的执行顺序和要执行的策略标识
        String key = CacheConstants.CACHE_PREFIX_CLIENT + standardSubmit.getClientID();
        String filters = cacheService.hGet(key, "filters");

        //3.遍历全部Strategy对象，根据执行顺序，依次执行策略方法
        for (String filter : filters.split(",")) {
            Strategy strategy = strategyObjects.get(filter);
            boolean flag = strategy.strategy(standardSubmit);  //flag==true   当前策略通过，继续执行下一个策略
            if (!flag){
                //当前策略执行失败，不能继续执行下一个策略
                //将错误信息发送到日志MQ
                log.info("【策略模块-策略执行器】 策略未通过，将错误信息发送到日志MQ  standardSubmit={},filter={}",standardSubmit,filter);
                pushMsgUtil.sendLog(standardSubmit, filter);
                //将状态报告发送给推送数据MQ
                log.info("【策略模块-策略执行器】 策略未通过，将状态报告发送给推送数据MQ  standardSubmit={},filter={}",standardSubmit,filter);
                pushMsgUtil.pushReport(standardSubmit, filter);
                break;
            }
        }
    }
}
